package rpcHandler

import (
	"context"
	"fmt"
	"gitee.com/zaiqiang231/go-base-session/app/config"
	"gitee.com/zaiqiang231/go-base-session/app/rpc/proto"
	"gitee.com/zaiqiang231/go-base-session/app/util"
	"sync"
	"time"
)

var (
	sessionSever     *SessionServer
	onceSessionSever sync.Once
)

type SessionServer struct {
}

func GetSessionServer() (*SessionServer, error) {
	onceSessionSever.Do(func() {
		sessionSever = &SessionServer{}
	})

	if sessionSever == nil {
		return nil, fmt.Errorf("got nil server")
	}

	return sessionSever, nil
}

func (s *SessionServer) TokenCreate(ctx context.Context, r *proto.TokenCreateRequest) (*proto.TokenCreateResponse, error) {
	token, err := config.GlobalJwtAuth.CreateToken(r.Identity, time.Duration(r.Timeout))
	return &proto.TokenCreateResponse{
		Token: token,
	}, err
}

func (s *SessionServer) TokenCheck(ctx context.Context, r *proto.TokenCheckRequest) (*proto.TokenCheckResponse, error) {
	isValid, identity, err := config.GlobalJwtAuth.TokenCheck(r.Token)
	var message string
	if err != nil {
		message = err.Error()
	} else {
		message = ""
	}
	return &proto.TokenCheckResponse{
		IsValid:  isValid,
		Identity: identity,
		Message:  message,
	}, nil
}

func (s *SessionServer) SessionCreate(ctx context.Context, r *proto.SessionCreateRequest) (*proto.SessionCreateResponse, error) {
	sid, err := util.CreateSession(ctx, uint64(r.Uid), uint64(r.ExpireTime), r.Cv)
	return &proto.SessionCreateResponse{
		Sid: sid,
	}, err
}

func (s *SessionServer) SessionCheck(ctx context.Context, r *proto.SessionCheckRequest) (*proto.SessionCheckResponse, error) {
	isValid, err := util.CheckSession(ctx, uint64(r.Uid), r.Sid)
	return &proto.SessionCheckResponse{
		IsValid: isValid,
	}, err
}
